package com.atguigu.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class HelloController {

    @Value("${git.From-Param}")


    String FromPath;


    @ResponseBody
    @RequestMapping("/hello")
    public String hello(@RequestBody Map params) {
        System.out.println(params.get("hook_url"));
        return "Hello World!";
    }

//    public String hello1(HttpServletRequest request, @RequestBody Map params) {

    @ResponseBody
    @RequestMapping("/")
    public String hello1(@RequestBody Map params) {
        String hook_url = params.get("hook_url").toString();
        System.out.println(hook_url);
        try {
            String url = "https://gitee.com/xia-xueqiu/huaweiRep/hooks/923705/edit";

            url = hook_url;

//        (\\w+://\\w+)(/w*)(/\\w*)(/\\w*)
            String str = "https://gitee.com/xia-xueqiu/huaweiRep/hooks/923705/edit";

            String url1 = "https://gitee.com-xia-xueqiu-huaweiRep/hooks/923705/edit";

            //  String regex = "([：-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)";
            String regex = "(\\w*://[-.\\w*]*[0-9a-zA-Z]*)\\/([-.\\w]*[0-9a-zA-Z]*)\\/([-.\\w]*[0-9a-zA-Z]*)\\/([/\\-.\\w]*[0-9a-zA-Z]*)";
//        String regex = "^(\\w+\\:\\/\\/\\w+)\\/(\\w+)\\/(\\w+\\/)(\\w+)$";
            //    String regex = "(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\'\\/\\\\&%\\+\\$#_=]*)?";
//        ((https://|http://)*)/((\\d{2})-(\\d{2}))
//System.out.println(str.matches(regex));

            Pattern pattern = Pattern.compile(regex);
            Matcher m = pattern.matcher(url);

            // group(),group(0)匹配整个表达式的子字符串
//        System.out.println(m.group());
//        System.out.println(m.group(0));
            // group(1),group(2)匹配对应分组


            String paramRespo = null;

            if (m.find()) {
                System.out.println(m.group(0));
                System.out.println("================");
                System.out.println(m.group(1));
                System.out.println(m.group(2));
                System.out.println(m.group(3));
                System.out.println(m.group(3));
                paramRespo = m.group(3);
                System.out.println(m.group(4));
            } else {
                System.out.println("不匹配");
            }


/*
            String shpath="/root/a.sh";
//            Process ps = Runtime.getRuntime().exec(shpath);
            Process ps = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/tmp/test2.sh param1"});

//             Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/tmp/test2.sh param1"});
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));




            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String result = sb.toString();
            System.out.println(result);
            return result;
        }
        catch (Exception e) {
            e.printStackTrace();
            return "error-------->";
        }

    }
*/


            //脚本路径
//            String shellPath = request.getServletContext().getRealPath("/") + "BOOT-INF/classes";
            String  shellPath ="/root/test";
            System.out.println(shellPath);
            shellPath="/root/test";
            paramRespo="huaweiRep";
            String cmd = shellPath + "/a.sh " + paramRespo;
            ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", cmd);
            builder.directory(new File(shellPath));
            //设置工作目录

            int runningStatus = 0;
            String s = null;
            StringBuffer sb = new StringBuffer();
            try {
                Process p = builder.start();

                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                while ((s = stdInput.readLine()) != null) {
//            LOG.info("shell log info ...." + s);
                    System.out.println(s);
                    sb.append(s);
                }
                while ((s = stdError.readLine()) != null) {
//            LOG.error("shell log error...." + s);
                    System.out.println(s);
                    sb.append(s);
                }


                try {
                    runningStatus = p.waitFor();
                } catch (InterruptedException e) {
                    runningStatus = 1;
//            LOG.error("等待shell脚本执行状态时，报错...",e);
                    sb.append(e.getMessage());
                }

                closeStream(stdInput);
                closeStream(stdError);

            } catch (Exception e) {
//                LOG.error("执行shell脚本出错...", e);
                sb.append(e.getMessage());
                runningStatus = 1;
            }

//            LOG.info("runningStatus = " + runningStatus);
            if (runningStatus == 0) {
                //成功
//                result.put("code", "1");
//                result.put("msg", "成功");
//                return result.toJSONString();
            } else {
//                result.put("code", "0");
//                result.put("msg", "调用shell脚本复制数据库时失败..." + sb.toString());
//                return result.toJSONString();
            }

        }
        catch (Exception e)
        {
             e.printStackTrace();
        }
            return "hello";




    }



    private void closeStream(BufferedReader reader){
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            reader = null;
        }
    }




    /*    public static void main(String[] args) {
        String url = "https://gitee.com/xia-xueqiu/huaweiRep/hooks/923705/edit";

//        (\\w+://\\w+)(/w*)(/\\w*)(/\\w*)
        String str = "https://gitee.com/xia-xueqiu/huaweiRep/hooks/923705/edit";

        String url1 = "https://gitee.com-xia-xueqiu-huaweiRep/hooks/923705/edit";

        //  String regex = "([：-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)/([-.\\\\w]*[0-9a-zA-Z]*)";
        String regex = "(\\w*://[-.\\w*]*[0-9a-zA-Z]*)\\/([-.\\w]*[0-9a-zA-Z]*)\\/([-.\\w]*[0-9a-zA-Z]*)\\/([/\\-.\\w]*[0-9a-zA-Z]*)";
//        String regex = "^(\\w+\\:\\/\\/\\w+)\\/(\\w+)\\/(\\w+\\/)(\\w+)$";
        //    String regex = "(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\'\\/\\\\&%\\+\\$#_=]*)?";
//        ((https://|http://)*)/((\\d{2})-(\\d{2}))
//System.out.println(str.matches(regex));

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(url);

        // group(),group(0)匹配整个表达式的子字符串
//        System.out.println(m.group());
//        System.out.println(m.group(0));
        // group(1),group(2)匹配对应分组


        if (m.find()) {
            System.out.println(m.group(0));
            System.out.println("================");
            System.out.println(m.group(1));
            System.out.println(m.group(2));
            System.out.println(m.group(3));
            System.out.println(m.group(3));
            System.out.println(m.group(4));
        } else {
            System.out.println("不匹配");
        }

    *//*    Pattern p = Pattern.compile("((https://|http://)*)/((\\d{2})-(\\d{2}))");
        Matcher m = p.matcher("2021-02-04");
        System.out.println(url.indexOf("gitee.com"));*//*
    }*/



}


/*
    public static void main(String[] args){
        try {
            String shpath="a.sh";
            Process ps = Runtime.getRuntime().exec(shpath);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String result = sb.toString();
            System.out.println(result);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
*/


//
///*    git bash  here
//    cd ~
//    pwd
///c/Users/Administrator.SC-201903101146
//
//    mkdir code-sync
//    cd code-sync
//
//
//
//
//1 cf.sh
//
//#!/bin/bash
//#公共变量
//# 本地缓存目录
//            BASE_DIR=~/code-sync/
//# /c/Users/Administrator.SC-201903101146*/










/*
//
//            #!/bin/bash
//# 引入公共变量
//#source cf.sh
//            BASE_DIR=~/code-sync/
//### 【TODO】按需修改下面参数即可：
//            # 项目名
//            PRO_NAME=huaweiRep3
//# 本地缓存目录-> 从公共变量cf.sh中获取
//# BASE_DIR=/Users/zxc/code-sync
//# 项目 源Git仓库地址(以/结尾)
//#FROM_GIT=https://github.com/xiaxueqiu/
//            # 项目 目标Git仓库地址（以/结尾）
//            #TO_GIT=https://gitee.com/xia-xueqiu/
//
//
//    FROM_GIT=https://gitee.com/xia-xueqiu/
//    TO_GIT=https://github.com/xiaxueqiu/
//            #TO_GIT=git@139.159.146.179:/home/gitrepo/huaweiRep3.git
//# 项目 目标Git仓库地址（以/结尾）
//
//
//
//
//    PRO_GIT_NAME=$PRO_NAME.git
//    cd $BASE_DIR
//    git clone --mirror $FROM_GIT$PRO_GIT_NAME
//    cd $PRO_GIT_NAME
//    git remote add --mirror=fetch secondary3 $TO_GIT$PRO_GIT_NAME
//
//# 开始第一次同步
//    git fetch origin
//    git push secondary3 --all
//
//
//# git remote add origin  git@139.159.146.179:/home/gitrepo/runoob.git
//# 生成每次同步的sh
//    cd $BASE_DIR
//    file_name="sync-${PRO_NAME}.sh"
//    cat > $file_name << EOF
//#!/bin/bash
//# 引入公共变量
//    source cf.sh
//    cd \$BASE_DIR
//    cd $PRO_GIT_NAME
//    git fetch origin
//    git push secondary --all
//            EOF
//
//# 授权可执行
//    chmod +x $file_name
*/



